package com.caojin.propertyInjector.locationResolver;

import java.io.InputStream;
import java.net.URLDecoder;

import com.caojin.propertyInjector.UrlResolver;
import com.caojin.util.FileUtil;

/**
 * 类路径解析器
 * 
 * @author caojin
 */
public class ClassPathLocationResolver extends LocationResolver {
	// 默认父包是根路径
	public final static String DEFAULT_BASE_PACKAGE = UrlResolver.PATH_SPLITOR;
	// classpath根目录的绝对路径
	public final static String CLASSPATH_ROOT = ClassPathLocationResolver.class
			.getResource(UrlResolver.PATH_SPLITOR).getPath();
	// 父包名
	private String basePackage;
	// 文件名
	private String fileName;
	// 是否递归
	private boolean recursive;

	public ClassPathLocationResolver() {
		this(DEFAULT_FILE_NAME);
	}

	public ClassPathLocationResolver(String fileName) {
		this(DEFAULT_BASE_PACKAGE, fileName);
	}

	public ClassPathLocationResolver(String basePackage, String fileName) {
		this(basePackage, fileName, Boolean.FALSE);
	}

	public ClassPathLocationResolver(String basePackage, String fileName,
			boolean recursive) {
		super(CLASSPATH_PREFIX);
		this.basePackage = basePackage;
		this.fileName = fileName;
		this.recursive = recursive;
	}

	@Override
	public InputStream getInputStream() {
		String classPathUrl = getBaseUrl();
		return ClassPathLocationResolver.class
				.getResourceAsStream(classPathUrl);
	}

	@Override
	protected String getBaseUrl() {
		if (recursive == Boolean.FALSE) {
			return UrlResolver.PATH_SPLITOR.concat(basePackage)
					.replaceAll("\\.", UrlResolver.PATH_SPLITOR)
					.concat(UrlResolver.PATH_SPLITOR).concat(fileName);
		} else {
			String decodeUrl = "";
			try {
				decodeUrl = URLDecoder.decode(CLASSPATH_ROOT, "UTF-8");
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			String filePath = FileUtil.getAbsolutePath(decodeUrl
					.concat(basePackage.replaceAll("\\.",
							UrlResolver.PATH_SPLITOR)), fileName);
			if (filePath != FileUtil.FILE_NOT_FOUND) {
				return UrlResolver.PATH_SPLITOR.concat(filePath
						.substring(decodeUrl.length() - 1));
			}
			throw new UnlocatedException("File Not Found: [basePackage="
					+ basePackage + ",fileName=" + fileName + "]");
		}
	}
}
